//
//  HZOrderViewController.m
//  Stock_Stategy
//
//  Created by MayerF on 2018/1/22.
//  Copyright © 2018年 MayerF. All rights reserved.
//

#import "HZOrderViewController.h"
#import "HZOrderView.h"

@interface HZOrderViewController ()
@property (nonatomic, strong)HZOrderView *pOrderView;
@property (nonatomic, strong)NSArray *pParams;
@property (nonatomic, copy)NSString *pPrice;
@property (nonatomic, copy)NSString *pCode;
@property (nonatomic, copy)NSString *pMarket;
@property (nonatomic, copy)NSString *pProductId;
@property (nonatomic, copy)NSString *pName;
@property (nonatomic, strong)HZStategyListModel *model;
@end

@implementation HZOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"条件单(创建策略)";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //关联逻辑管理对象
    self.logicManager = [HZBaseLogjcManager new];
    self.view.logicManager = self.logicManager;
    
    _pOrderView = [HZOrderView new];
    [self.view addSubview:_pOrderView];
    [_pOrderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    if ([self.params.allKeys containsObject:@"type"]) {// type=1 买入 2卖出
        NSString *type = self.params[@"type"];
        if ([type isEqual:@"1"]) {
            self.title = @"条件单（创建策略）";
            NSArray *orderParams = nil;
            NSArray *otherParams = nil;
            if ([self.params.allKeys containsObject:@"params"]) {
                orderParams = self.params[@"params"];
            }
            if ([self.params.allKeys containsObject:@"other"]) {
                otherParams = self.params[@"other"];
            }
            _pName = orderParams[0];
            _pCode = otherParams[0];
            _pMarket = otherParams[1];
            _pPrice = otherParams[2];
            _pProductId = otherParams[3];
            if (orderParams && _pCode) {
                NSMutableArray *tempArray = [NSMutableArray arrayWithArray:orderParams];
                [tempArray replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:@"%@/%@",_pCode,orderParams[0]]];
                _pParams = tempArray;
            }
        }else {
            self.title = @"条件单（卖出策略）";
            if ([self.params.allKeys containsObject:@"params"]) {
                _model = self.params[@"params"];
                _pParams = @[[NSString stringWithFormat:@"%@/%@",_model.product_code, _model.product_name],_model.serial_no,[NSString stringWithFormat:@"%@股",_model.open_amount],[NSString stringWithFormat:@"%@元/股",_model.entrust_price]];
                _pPrice = _model.last_price;
            }
        }
    }
    
    
    [self p_registerBlock];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (_model) {
        [_pOrderView updateName:@[@"策略标的",@"策略编号",@"股票数量",@"买入价格"]];
    }
    [_pOrderView updateData:_pParams price:_pPrice];
}

#pragma mark -
#pragma mark blockAction
- (void)p_registerBlock
{
    __weak typeof (self)weakSelf = self;
    [self.logicManager mapLogic:kLogicRouterAddOrder toBlock:^id(NSDictionary *params, id other) {
        BOOL isSelected = [other boolValue];
        if (!isSelected) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"你必须同意《服务协议》才能添加条件单" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertVC addAction:actionOk];
            [self presentViewController:alertVC animated:YES completion:nil];
            return nil;
        }
        [weakSelf addOrderWithOther:params];
        return nil;
    }];
}

- (void)addOrderWithOther:(id)other
{
    NSString *title = @"添加条件单（卖出策略）需要冻结履约保证金 + 综合服务费";
    if (_model) {
        title = @"确定要添加条件单（卖出策略）吗？";
    }
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        if (_model) {
            [self p_sendRequestAddSellOrderWithOther:other];
        }else {
            [self p_sendRequestAddOrderWithOther:other];
        }
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:actionOk];
    [alertVC addAction:actionCancel];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)p_sendRequestAddOrderWithOther:(id)other
{
    NSString *type = other[@"type"];
    NSString *direction = other[@"direction"];
    NSString *price = other[@"price"];
    NSString *time = other[@"time"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"300039", kAPIFuctionKey,
                          _pProductId, @"prodcut_id",
                          _pCode, @"product_code",
                          _pName, @"product_name",
                          _pMarket, @"market",
                          price, @"efficient_price",
                          time, @"efficient_time",
                          type, @"trigger_type",
                          direction, @"trigger_direction",
                          nil];
    [HZApiManager apiPostParams:dict success:^(id objc) {
        [SVProgressHUD showSuccessWithStatus:@"条件单添加成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_pOrderView clearData];
        });
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}
- (void)p_sendRequestAddSellOrderWithOther:(id)other
{
    NSString *type = other[@"type"];
    NSString *direction = other[@"direction"];
    NSString *price = other[@"price"];
    NSString *time = other[@"time"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"300040", kAPIFuctionKey,
                          _model.serial_no, @"source_contract_no",
                          price, @"efficient_price",
                          time, @"efficient_time",
                          type, @"trigger_type",
                          direction, @"trigger_direction",
                          nil];
    [HZApiManager apiPostParams:dict success:^(id objc) {
        [SVProgressHUD showSuccessWithStatus:@"条件单添加成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_pOrderView clearData];
        });
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}

@end
